package com.jhf.youke.base.adapter.web;

import com.jhf.youke.base.app.executor.PermissionsSetAppService;
import com.jhf.youke.base.app.executor.UserAppService;
import com.jhf.youke.base.domain.exception.UserException;
import com.jhf.youke.base.domain.model.dto.RegisterCustomerDto;
import com.jhf.youke.base.domain.model.dto.RegisterRegimentalCommanderDto;
import com.jhf.youke.base.domain.model.dto.UserDto;
import com.jhf.youke.base.domain.model.vo.UserVo;
import com.jhf.youke.core.entity.Pagination;
import com.jhf.youke.core.entity.Response;
import com.jhf.youke.core.entity.User;
import com.jhf.youke.core.utils.CacheUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.*;

/**
 * 系统用户(User)表控制层
 * @author RHJ
 */
@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserAppService userAppService;

    @Resource
    private PermissionsSetAppService permissionsSetAppService;

    @PostMapping("/update")
    @ApiOperation("更新")
    public Response<Boolean> update(@RequestBody UserDto dto) {
        return Response.ok(userAppService.update(dto));
    }

    @PostMapping("/delete")
    @ApiOperation("删除")
    public Response<Boolean> delete(@RequestBody UserDto dto) {
        return Response.ok(userAppService.delete(dto));
    }

    @PostMapping("/insert")
    @ApiOperation("插入")
    public Response<Boolean> insert(@RequestBody UserDto dto) {
        return Response.ok(userAppService.insert(dto));
    }

    @GetMapping("/findById")
    @ApiOperation("根据ID查询")
    public Response<Optional<UserVo>> findById(Long id) {
        return Response.ok(userAppService.findById(id));
    }

    @GetMapping("/remove")
    @ApiOperation("标记删除")
    public Response<Boolean> remove(Long id) {
        return  Response.ok(userAppService.remove(id));
    }

    @PostMapping("/removeBatch")
    @ApiOperation("批量标记删除")
    public Response<Boolean> removeBatch(@RequestBody List<Long> idList) {
        return  Response.ok(userAppService.removeBatch(idList));
    }

    @PostMapping("/list")
    @ApiOperation("列表查询")
    public Response<List<UserVo>> list(@RequestBody UserDto dto) {
        return Response.ok(userAppService.findAllMatching(dto));
    }

    @PostMapping("/selectPage")
    @ApiOperation("分页查询")
    public Response<Pagination<UserVo>> selectPage(@RequestBody  UserDto dto, @RequestHeader("token") String token) {
        return Response.ok(userAppService.selectPage(dto, token));
    }

    @PostMapping("/addRoles")
    @ApiOperation("分页查询")
    public Response<Boolean> addRoles(@RequestBody  UserDto dto) {
        return Response.ok(userAppService.addRoles(dto));
    }

    @GetMapping("/getInfoAndRols")
    @ApiOperation("根据ID查询用户权限")
    public Response<Map<String,Object>> getInfoAndRols(@RequestHeader("token") String token) throws Exception{
        User user = CacheUtils.getUser(token);
        Map<String, Object> data = permissionsSetAppService.getPermissionCodeList(user.getId());
        if(user != null) {
            data.put("user", userAppService.findById(user.getId()));
        }
        return Response.ok(data);
    }

    @GetMapping("/getInfo")
    @ApiOperation("根据token查询")
    public Response<Optional<UserVo>> getInfo(@RequestHeader("token") String token) throws Exception{
        User user = CacheUtils.getUser(token);
        return Response.ok(userAppService.findById(user.getId()));
    }

    @PostMapping("/updateInfo")
    @ApiOperation("用户修改自己的信息")
    public Response<Boolean> updateInfo(@RequestHeader("token") String token, @RequestBody UserDto dto) throws Exception{
        User user = CacheUtils.getUser(token);
        return Response.ok(userAppService.updateInfoByUserId(user.getId(), dto));
    }

    @PostMapping("/updatePassword")
    @ApiOperation("用户修改自己的密码")
    public Response<Boolean> updatePassword(@RequestHeader("token") String token, @RequestBody UserDto dto) throws Exception{
        try {
            User user = CacheUtils.getUser(token);
            return Response.ok(userAppService.updatePasswordByUserId(user.getId(), dto));
        }catch (UserException e){
            return Response.fail(e.getMessage());
        }
    }

    @PostMapping("/resetPassword")
    @ApiOperation("重置用户密码")
    public Response<Boolean> resetPassword(@RequestBody UserDto dto){
        try {
            return Response.ok(userAppService.resetPassword(dto));
        }catch (UserException e){
            return Response.fail(e.getMessage());
        }
    }

    @PostMapping("/updateStatus")
    @ApiOperation("更新用户状态")
    public Response<Boolean> updateStatus(@RequestBody UserDto dto) {
        try {
            return Response.ok(userAppService.updateStatus(dto));
        }catch (UserException e){
            return Response.fail(e.getMessage());
        }
    }

    @PostMapping("/registerRegimentalCommander")
    @ApiOperation("邀请注册团长")
    public Response<Boolean> registerRegimentalCommander(@RequestBody @Validated RegisterRegimentalCommanderDto dto) {
        return Response.ok(userAppService.registerRegimentalCommander(dto));
    }


    @PostMapping("/registerCustomer")
    @ApiOperation("邀请注册客户")
    public Response<Boolean> registerCustomer(@RequestBody @Validated RegisterCustomerDto dto) {
        return Response.ok(userAppService.registerCustomer(dto));
    }

    @GetMapping("/test")
    public String test(){

        ThreadPoolExecutor  pool = new ThreadPoolExecutor(
                5,
                10,
                30,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<Runnable>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        int num = 10;
        for(int i = 0;i<num;i++){
            //向线程池提交一个任务（其实就是通过线程池来启动一个线程）
            pool.execute(new Runnable(){
                @Override
                public void run() {
                    userAppService.test();
                }
            });

        }

        return "1111";
    }

}

